package com.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.task.SseClient;
import com.util.CurrentUser;
import com.util.controller.util.HtmlToPdf;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: xuan
 * @Date: 2024/7/4 11:03
 * @Version: 1.0
 */
@Slf4j
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/exportPdf")
    public void exportPdf(HttpServletResponse response) {
        // ========== pdf处理方式 ===========
        //一个map是一行，key为属性值，value为存储值。
        log.info("开始生成pdf");
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "赵小刚");
        map1.put("phone", "15673890987");
        map1.put("nickname", "红孩儿");
        map1.put("email", "15673890987@163.com");
        map1.put("num","10086");

        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "赵小刚");
        map2.put("phone", "15673890987");
        map2.put("nickname", "红孩儿");
        map2.put("email", "15673890987@163.com");
        map2.put("num","10000");
        //存入list中
        List<Map<String, Object>> stuffList = Arrays.asList(map1,map2);

        Map<String, Object> stuffMap = new HashMap<>();
        //把列和数值放在map内
        stuffMap.put("params", stuffList);
        //内容标题
        stuffMap.put("title", "测试PDF模板");
    System.out.println("stuffMap = " + stuffMap);

        File pdfFile = FileUtil.file("test.pdf");
        try (OutputStream os = new FileOutputStream(pdfFile);) {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
            // 如果填充值中与模板不匹配，或者为null值，则默认此值为空；
            cfg.setClassicCompatible(true);
            // 模板路径加载方式：基于类路径，即在src\main\resources\templates包下的ftl模板
            cfg.setClassForTemplateLoading(this.getClass(),"/templates");
            Template template = cfg.getTemplate( "free.ftl");
            Writer writer = new StringWriter();
            template.process(stuffMap, writer);

            // 对pdf资料进行创建
            HtmlToPdf.htmlToPdf(writer.toString(),os);
            byte[] dataByte = FileUtil.readBytes(pdfFile);

            response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(dataByte.length));
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s"
                    , URLEncoder.encode("pdf测试.pdf", "UTF-8")));
            IoUtil.write(response.getOutputStream(), Boolean.TRUE, dataByte);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出贷后检查表失败, 详情：{}", e.getMessage());
        } finally {
            // 删除项目classes/目录下生成的临时文件
            if (pdfFile.exists()) {
                FileUtil.del(pdfFile);
            }
        }


    }




  /*  @Autowired
    private SseClient sseClient;
    @Autowired
    private CurrentUser currentUser;

    @GetMapping("/createSse")
    public SseEmitter createConnect() {
        return sseClient.createSse(currentUser.getCurrentEname());
    }

    @GetMapping("/sendMsg")
    @ResponseBody
    public String sseChat() {
        for (int i = 0; i < 10; i++) {
            sseClient.sendMessage(currentUser.getCurrentEname(), "no" + i, IdUtil.fastUUID());
        }
        return "ok";
    }*/

    /**
     * 关闭连接
     *//*
    @CrossOrigin
    @GetMapping("/closeSse")
    public void closeConnect() {

        sseClient.closeSse(currentUser.getCurrentEname());
    }*/
}